import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/**
 * Create by chenhd on 2021/8/28.
 * 方法五：使用StampedLock,这种锁属于不可重入锁，个人认为在生产环境中少用，很容易出现问题，除非你知道自己在干什么
 */
public class ConcurrentTask5 {
    public String str;
    public StampedLock lock = new StampedLock();

    public static void main(String[] args) {
        ConcurrentTask5 concurrentTask = new ConcurrentTask5();

        //注意不能是读-读锁，因为读-读不互斥
        long writeStamp = concurrentTask.lock.writeLock();
        new Thread(() -> concurrentTask.putStr(writeStamp)).start();

        long readStamp = concurrentTask.lock.readLock();
        System.out.println(concurrentTask.getStr());

        concurrentTask.lock.unlock(readStamp);
    }

    public void putStr(long stamp) {
        try {
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
            lock.unlock(stamp);
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        }
    }

    public String getStr() {
        return str;
    }
}
